package com.admin_system.controller;

import com.admin_system.pojo.User;
import com.admin_system.service.UserService;
import com.admin_system.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    /**
     * 检查令牌是否即将过期
     * 
     * @param authHeader 认证头部，包含JWT令牌
     * @return 包含令牌状态的响应
     */
    @PostMapping("/check-token-expiry")
    public ResponseEntity<?> checkTokenExpiry(@RequestHeader("Authorization") String authHeader) {
        try {
            // 从认证头部提取令牌
            String token = authHeader.substring(7); // 移除"Bearer "前缀
            
            // 检查令牌是否即将过期
            boolean isNearExpiry = jwtTokenUtil.isTokenNearExpiry(token);
            
            Map<String, Object> response = new HashMap<>();
            response.put("nearExpiry", isNearExpiry);
            
            if (isNearExpiry) {
                logger.debug("令牌即将过期，建议刷新");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("检查令牌过期状态时出错", e);
            return ResponseEntity.badRequest().body(Map.of(
                "error", "invalid_token",
                "message", "无效的令牌"
            ));
        }
    }
    
    /**
     * 刷新用户令牌
     * 用于前端在令牌即将过期时主动刷新
     * 
     * @return 包含新令牌的响应
     */
    @PostMapping("/refresh-token")
    public ResponseEntity<?> refreshToken() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            
            if (user != null) {
                // 生成新的token
                String token = userService.generateUserToken(user);
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("token", token);
                response.put("username", user.getUsername());
                response.put("fullName", user.getFullName());
                response.put("role", user.getRole());
                
                logger.info("已为用户 {} 刷新令牌", username);
                return ResponseEntity.ok(response);
            }
        }
        
        return ResponseEntity.status(401).body(Map.of(
            "success", false,
            "message", "未授权，无法刷新令牌"
        ));
    }
    
    /**
     * 用户登出
     * 使当前用户的所有令牌失效
     * 
     * @return 登出结果
     */
    @PostMapping("/logout")
    public ResponseEntity<?> logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            String username = authentication.getName();
            userService.invalidateUserTokens(username);
            logger.info("用户 {} 已登出", username);
            return ResponseEntity.ok(Map.of("success", true));
        }
        return ResponseEntity.ok(Map.of("success", false));
    }
} 